package com.bw.shopping.mvvm.viewmodel;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.blankj.utilcode.util.LogUtils;
import com.bw.greendao.dao.DaoSessionUtils;
import com.bw.greendao.dao.ShoppEntityDao;
import com.bw.greendao.entity.ShoppDaoEntity;
import com.bw.greendao.entity.ShoppEntity;
import com.bw.greendao.entity.UserDaoEntity;
import com.bw.greendao.entity.UserEntity;
import com.bw.mvvm_common.BaseApplication;
import com.bw.mvvm_common.entity.BaseEntity;
import com.bw.mvvm_common.filed.UIField;
import com.bw.mvvm_common.mvvm.viewmodel.BaseViewModel;
import com.bw.mvvm_common.utils.IntentAction;
import com.bw.shopping.R;
import com.bw.shopping.adapter.OfflineAdapter;
import com.bw.shopping.adapter.ShoppingAdapter;
import com.bw.shopping.entity.AddShoppEntity;
import com.bw.shopping.entity.DelShopEntity;
import com.bw.shopping.entity.ShoppingEnttiy;
import com.bw.shopping.entity.SubmitCarEntity;
import com.bw.shopping.mvvm.model.ShoppingModel;
import com.bw.shopping.mvvm.view.OrderListActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author KK
 * @description:
 * @date :2021/10/21 19:35
 */
public class ShoppingViewModel extends BaseViewModel<ShoppingModel> implements OnItemChildClickListener{

    public ObservableField<BaseQuickAdapter> adapters = new ObservableField<>();
    public ObservableField<String> tv = new ObservableField<>("编辑");
    public ObservableField<Boolean> checkAll = new ObservableField<>(false);
    public ObservableField<String> price = new ObservableField<>("0.00");
    ShoppingEnttiy shoppingsEnttiy;
    private List<Integer> cartIdList = new ArrayList<>();
    private float money=0f;

    @Override
    protected void result(BaseEntity baseEntity) {
        if(baseEntity instanceof ShoppingEnttiy){
            ShoppingEnttiy shoppingEnttiy = (ShoppingEnttiy) baseEntity;
            shoppingsEnttiy = (ShoppingEnttiy) baseEntity;
            adapters.set(new ShoppingAdapter());
            adapters.get().setOnItemChildClickListener(this);
            adapters.get().setNewInstance(shoppingEnttiy.getData());
        }else if(baseEntity.getMessage().equals("列表为空")){
            showMsg("列表为空");
            return;
        }

        if(baseEntity.getMessage().equals("购物车提交成功")){
            showMsg("正在生成订单");
            /////////删除
            int itemCount = adapters.get().getItemCount();
            for (int i = 0; i < itemCount; i++) {
                if(shoppingsEnttiy.getData().get(i).isSelect()){
                    cartIdList.add(shoppingsEnttiy.getData().get(i).getId());
                }
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("cartIdList",cartIdList);
            m.requestDelShopp(map)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(this);
            ///////////////////////
            SubmitCarEntity submitCarEntity = (SubmitCarEntity) baseEntity;
            int data = submitCarEntity.getData();
            IntentAction intentAction = new IntentAction();
            intentAction.ation = "sendOrder";
            intentAction.num = data;
            intentAction.money = price.get();
            EventBus.getDefault().postSticky(intentAction);
            LogUtils.e(shoppingsEnttiy.getData());
            HashMap<String, Object> maps = new HashMap<>();
            maps.put(UIField.PAGECLAZZ, OrderListActivity.class);
            startPage(maps);
        }
    }

    @Override
    public void oncreate() {
        super.oncreate();
        islogin();

    }

    public void islogin(){
        List<UserEntity> list = DaoSessionUtils.getInstance().getSession().queryBuilder(UserEntity.class).list();
        //判断登录状态
        if(list==null){
            return;
        }else {
            if(list.get(0).getFlag()){
                //登录请求在线购物车
                requestShoppList();

            }else {
                //未登录请求离线购物车
                requestOffline();
            }

        }

    }

    //在线购物车
    public void requestShoppList(){
        HashMap<String, Object> map = new HashMap<>();
        List<UserEntity> list = DaoSessionUtils.getInstance().getSession().queryBuilder(UserEntity.class).list();
        if(list==null){
            return;
        }else {
            map.put("id",list.get(0).getUser_id());
            m.requestShopping(map)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(this);
            List<ShoppEntity> sqlist = DaoSessionUtils.getInstance().getSession().queryBuilder(ShoppEntity.class).list();
            for (ShoppEntity shoppEntity : sqlist) {
                HashMap<String, Object> maps = new HashMap<>();
                maps.put("goodsDesc",shoppEntity.getGoods_desc());
                maps.put("goodsIcon",shoppEntity.getGoods_default_icon());
                maps.put("goodsId",shoppEntity.getGoods_id());
                maps.put("goodsPrice",shoppEntity.getGoods_price());
                maps.put("goodsSku",shoppEntity.getGoods_default_sku());
                maps.put("time",System.currentTimeMillis());
                maps.put("userId",list.get(0).getUser_id());
                m.requestShoppAdd(maps)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe(this);
            }
            DaoSessionUtils.getInstance().getSession().deleteAll(ShoppEntity.class);

        }

    }

    //离线购物车
    public void requestOffline(){
        List<ShoppEntity> list = DaoSessionUtils.getInstance().getSession().queryBuilder(ShoppEntity.class).list();
        if(list!=null){
            adapters.set(new OfflineAdapter());
            adapters.get().setNewInstance(list);
        }
    }


    //编辑
    public void sets(){
        List<ShoppingEnttiy.DataBean> data = adapters.get().getData();
        if(data.size()==0){
            return;
        }
        List<ShoppingEnttiy.DataBean> list = new ArrayList<>();
        for (ShoppingEnttiy.DataBean values : data) {
            values.editSelect = !values.editSelect;
            list.add(values);
        }
        if(list.get(0).editSelect){
            tv.set("完成");
        }else {
            tv.set("编辑");
        }
        adapters.get().setNewInstance(list);
    }

    //全选
    public void checkall(){
        money=0f;
        List<ShoppingEnttiy.DataBean> data = adapters.get().getData();
        if(!data.get(0).editSelect){
            showMsg("不是编辑状态");
            return;
        }else {
            if(data.size()==0){
                checkAll.set(false);
            }
            boolean allFlag = !checkAll.get();
            checkAll.set(allFlag);
            List<ShoppingEnttiy.DataBean> datas = new ArrayList<>(data);
            for (int i = 0; i < datas.size(); i++) {
                datas.get(i).isSelect = allFlag;
                money+=(Float.valueOf(TextUtils.isEmpty(datas.get(i).goods_price)?"0":datas.get(i).getGoods_price())*datas.get(i).goods_count);

            }
            adapters.get().setNewInstance(datas);
        }




        price.set(money+"");

    }

    //价格
    public void checxMoney(){
        money=0f;
        price.set("0.00");
        List<ShoppingEnttiy.DataBean> data = adapters.get().getData();
        if(data.size() == 0){
            price.set("0.00");
            return;
        }

        for (ShoppingEnttiy.DataBean datum : data) {
            if(datum.isSelect){
                money+=(Float.valueOf(TextUtils.isEmpty(datum.goods_price)?"0":datum.getGoods_price())*datum.goods_count);
            }
        }
        price.set(money+"");

    }

    //去结算
    public void submitCar(){
        //接口map
        HashMap<String, Object> map = new HashMap<>();
        //提交订单的list
        List<HashMap<String,Object>> list = new ArrayList<>();
        List<ShoppingEnttiy.DataBean> data = adapters.get().getData();
        if(data.size()==0){
            showMsg("没数据,请先添加");
            return;
        }else {
            int itemCount = adapters.get().getItemCount();
            for (int i = 0; i < itemCount; i++) {
                if(data.get(i).isSelect){
                    HashMap<String, Object> map1 = new HashMap<>();
                    map1.put("goods_count",data.get(i).getGoods_count());
                    map1.put("goods_desc",data.get(i).getGoods_desc());
                    map1.put("goods_icon",data.get(i).getGoods_icon());
                    map1.put("goods_id",data.get(i).getGoods_id());
                    map1.put("goods_price",data.get(i).getGoods_price());
                    map1.put("goods_sku",data.get(i).getGoods_sku());
                    map1.put("id",data.get(i).getId());
                    map1.put("order_id",0);
                    list.add(map1);
                }
            }
            List<UserEntity> list1 = DaoSessionUtils.getInstance().getSession().queryBuilder(UserEntity.class).list();
            map.put("goodsList",list);
            map.put("totalPrice",Float.valueOf(price.get()));
            map.put("userId",list1.get(0).getUser_id());

            m.requestSubmitCar(map)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(this);


        }

    }








    @Override
    public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {

        ShoppingEnttiy.DataBean item = (ShoppingEnttiy.DataBean) adapter.getItem(position);
        if(!item.editSelect){
            showMsg("不是编辑状态");
            return;
        }
        //减
        if(R.id.lbtn == view.getId()){
            item.goods_count--;
            if(item.goods_count<0){
                item.goods_count=0;
            }
            //加
        }else if(R.id.rbtn == view.getId()){
           item.goods_count++;
        }else if(R.id.item_chex == view.getId()){
            item.isSelect = !item.isSelect;


        }

        checxMoney();
        adapters.get().setData(position,item);
    }
}
